package edu.ustb.efws.base.controller;

import edu.ustb.efws.base.controller.form.DetectorSaveForm;
import edu.ustb.efws.base.controller.form.DetectorUpdateForm;
import edu.ustb.efws.base.domain.Detector;
import edu.ustb.efws.base.service.DetectorService;
import edu.ustb.efws.controller.vo.OkVo;
import edu.ustb.efws.controller.vo.ResultPageVo;
import edu.ustb.efws.controller.vo.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 设备管理
 *
 * @author TS Group
 */
@RestController
@RequestMapping("/manage/detector")
@Api(value = "/manage/detector", tags = "设备管理")
public class DetectorController {
    private final DetectorService service;

    @Autowired
    public DetectorController(DetectorService service) {
        this.service = service;
    }

    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("新增设备")
    public ResultVo<Detector> save(@Valid @RequestBody DetectorSaveForm form){
        return ResultVo.success(service.save(form.toDomain()));
    }

    @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("修改设备")
    public ResultVo<Detector> update(@Valid @RequestBody DetectorUpdateForm form){
        return ResultVo.success(service.update(form.toDomain()));
    }

    @DeleteMapping(value = "{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("删除设备")
    public ResultVo<OkVo> delete(@PathVariable("id")int id){
        return ResultVo.success(new OkVo(service.delete(id)));
    }

    @GetMapping(value = "{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("得到设备")
    public ResultVo<Detector> get(@PathVariable("id")int id){
        return ResultVo.success(service.get(id));
    }

    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("查询设备")
    public ResultPageVo<Detector> query(
            @ApiParam(value = "设备类型") @RequestParam(required = false) String detectorType,
            @ApiParam(value = "设备名称") @RequestParam(required = false) String description,
            @RequestParam(defaultValue = "true") @ApiParam(value = "是否查询记录数") Boolean isCount,
            @RequestParam(defaultValue = "0") @ApiParam(value = "查询页数") int page,
            @RequestParam(defaultValue = "15") @ApiParam(value = "查询每页记录数") int rows){

        return new ResultPageVo
                .Builder<>(page, rows, service.query(detectorType, description, page * rows, rows))
                .count(isCount, () -> service.count(detectorType, description))
                .build();
    }
}
